export default class joystick extends Laya.Script {
    /** @prop {name:stick,tips:"触摸中心点",type:Node,default:null } */
    stick:Laya.Node = null;
    
    /** @prop {name:max_R,tips:"触摸中心点",type:number,default:80 } */
    max_R:number = 80;

    private stick_flag:boolean = false;

    public dir: Laya.Point = Laya.Point.create();
    constructor() { super(); }
    
    onEnable(): void {
        //this.stick.on(Laya.Event.MOUSE_DOWN,this,this.stick_start);
        this.stick.on(Laya.Event.MOUSE_DOWN,this,this.stick_start);
        Laya.stage.on(Laya.Event.MOUSE_OUT,this,this.stick_end);
        Laya.stage.on(Laya.Event.MOUSE_MOVE,this,this.stick_move);  
        // Laya.stage.on(Laya.Event.MOUSE_OUT,this,this.stick_test); 
    }

    stick_test(){
        console.log('stick_test')
    }

    stick_start(){
        this.stick_flag = true;
        console.log('stick start'); 
    }

    stick_move(){
        if(this.stick_flag == false)
        {
            return;
        }  

        var pos: Laya.Point = Laya.Point.create(); 
        pos.x = Laya.stage.mouseX;
        pos.y = Laya.stage.mouseY;
       
        //将世界坐标转变成本地坐标
        var self_node: Laya.Sprite = this.owner as Laya.Sprite;
        self_node.globalToLocal(pos);
        
        var xpos: number = pos.x;
        var ypos: number = pos.y;
        var len: number = pos.distance(0, 0);
        
        if (len > this.max_R) {
            pos.x = pos.x * this.max_R / len;
            pos.y = pos.y * this.max_R / len; 
        }

        var stick_node: Laya.Sprite = this.stick as Laya.Sprite;        
        
        stick_node.pos(pos.x, pos.y);        
        self_node.globalToLocal(pos); 
        this.dir.x = xpos / len;
        this.dir.y = ypos / len;  
    }

    stick_end(){
        if(this.stick_flag == false)
        {
            return;
        }
        this.stick_flag = false;
        var stick_node: Laya.Sprite = this.stick as Laya.Sprite;
        stick_node.pos(0, 0);
        this.dir.x =0;
        this.dir.y =0;
        console.log('stick end');
    }

    stick_over(){
        console.log('stick over');
    }

    onDisable(): void {
    }
}